import 'package:flutter/material.dart';

class FutureAndStream extends StatelessWidget {
  // 模拟网络请求数据
  Future<String> mockNetworkData() async {
    return Future.delayed(Duration(seconds: 2), () => "我是从互联网上获取的数据");
  }

  // 模拟数据流
  // TODO 怎么停止Stream
  Stream<int> counter() {
    return Stream.periodic(Duration(seconds: 1), (i) => i); //每隔1s，计数加1
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("异步UI更新"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text("FutureBuilder:"),
            FutureBuilder<String>(
              future: mockNetworkData(),
              builder: (BuildContext context, AsyncSnapshot snapshot) {
                if (snapshot.connectionState == ConnectionState.done) {
                  //请求结束
                  if (snapshot.hasError) {
                    //请求失败，显示错误
                    return Text("Error: ${snapshot.error}");
                  } else {
                    //请求成功，显示数据
                    return Text("Data: ${snapshot.data}");
                  }
                } else {
                  //请求中，显示loading
                  return CircularProgressIndicator();
                }
              },
            ),
            Container(
              height: 50.0,
            ),
            Text("StreamBuilder:"),
            StreamBuilder(
              stream: counter(),
              builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
                if (snapshot.hasError) {
                  return Text("Error: ${snapshot.error}");
                }
                switch (snapshot.connectionState) {
                  case ConnectionState.none:
                    return Text("没有Stream");
                  case ConnectionState.waiting:
                    return Text("等待数据...");
                  case ConnectionState
                      .active: //Stream处于激活状态（流上已经有数据传递了），对于FutureBuilder没有该状态。
                    return Text("active: ${snapshot.data}");
                  case ConnectionState.done:
                    return Text("Stream已关闭");
                  default:
                    return null;
                }
              },
            ),
          ],
        ),
      ),
    );
  }
}
